# -*-coding:utf-8-*-

from rest_framework.fields import SerializerMethodField

from rest_framework import serializers

from calculator.models import AreaCode, IndusAverWage, IncomeExpendItem, Industry, ResIncomeExpend
from rest_framework.serializers import ModelSerializer

__author__ = 'malixin'


class AreaCodeSerializer(ModelSerializer):
    """地区编码"""
    children = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AreaCode
        fields = [
            'code',
            'name',
            'children',
        ]

    def get_children(self, obj):
        queryset = self.Meta.model.objects.extra(where=['left(code,2)=%s', 'length(code)=4'], params=[obj.code])
        if queryset:
            return self.__class__(queryset, many=True).data
        else:
            return None


class ProvinceSerializer(ModelSerializer):
    """省级编码"""
    class Meta:
        model = AreaCode
        fields = [
            'code',
            'name',
        ]


class IndusAverWageSerializer(ModelSerializer):
    """分行业城镇单位在岗职工平均工资"""
    province_name = serializers.CharField(source="province.name", read_only=True)
    industry_name = serializers.CharField(source="industry.name", read_only=True)

    class Meta:
        model = IndusAverWage
        fields = [
            'id',
            'province',
            'province_name',
            'industry',
            'industry_name',
            'years',
            'aver_wage',
            'day_aver_wage',
        ]


class IncomeExpendItemSerializer(ModelSerializer):
    """居民人均收支项"""

    class Meta:
        model = IncomeExpendItem
        fields = "__all__"


class ResIncomeExpendSerializer(ModelSerializer):
    """居民人均收支情况表"""
    province_name = serializers.CharField(source="province.name", read_only=True)
    item_name = serializers.CharField(source="inc_exp_item.name", read_only=True)

    class Meta:
        model = ResIncomeExpend
        fields = ["id", "province", "province_name", "inc_exp_item", "item_name", "years", "total_money"]


class IndustrySerializer(ModelSerializer):
    """行业管理"""
    standard_name = serializers.CharField(source="get_standard_display", read_only=True)

    class Meta:
        model = Industry
        fields = ["id", "name", "standard", "standard_name"]


